import React, { useEffect, useState, useRef } from "react";
import moment from 'moment'
import './TimeBack.css'

const TimeBack = () => {
  const [current, setTime] = useState("00 : 00 : 00 ");

  const timerID = useRef();

  const deadLine = moment('2022-1-22 20:40:25');

  const deadLineTime = deadLine.diff(moment())

  let durationTime = moment.duration(deadLineTime);

  let isArrived = deadLineTime < 0;

  useEffect(() => {
    timerID.current = setInterval(() => {
      let arriveTime = `${durationTime.hours()}:${durationTime.minutes()}:${durationTime.seconds()}`;
      if (!isArrived) {
        durationTime = moment.duration(deadLine.diff(moment()));
        setTime(() => arriveTime); // make pretty
      }
    }, 1000);
  }, []);

  useEffect(() => {
    if (isArrived) {
      clearInterval(timerID.current);
    }
  });

  return (
    <div>
      {current}
    </div>
  );
}

export default TimeBack